<template>
  <div class="app-container">
    <el-button-group style="margin-bottom: 16px;">
      <el-button @click="goTo('/content/announcement')">公告管理</el-button>
      <el-button @click="goTo('/content/carousel')">轮播图</el-button>
      <el-button @click="goTo('/permission/role')">角色管理</el-button>
      <el-button @click="goTo('/system/basic')">系统配置</el-button>
    </el-button-group>
    <!-- 搜索和操作栏 -->
    <div class="filter-container">
      <el-input v-model="queryParams.title" placeholder="帮助标题" clearable class="filter-item" style="width: 200px;" @keyup.enter="handleQuery" />
      
      <el-select v-model="queryParams.category" placeholder="分类" clearable class="filter-item" style="width: 120px;">
        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      
      <el-select v-model="queryParams.status" placeholder="状态" clearable class="filter-item" style="width: 120px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      
      <el-button type="primary" class="filter-item" @click="handleQuery">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button type="success" class="filter-item" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="helpList"
      border
      style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" />
      <el-table-column label="标题" prop="title" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="分类" prop="category" width="120">
        <template #default="{ row }">
          <el-tag :type="getCategoryTagType(row.category)">
            {{ getCategoryName(row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="80" />
      <el-table-column label="浏览量" prop="viewCount" width="100" align="center" />
      <el-table-column label="更新时间" prop="updateTime" width="160" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="row.status === 'published' ? 'warning' : 'success'" 
            @click="handleToggleStatus(row)">
            {{ row.status === 'published' ? '下线' : '发布' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination-container"
    />

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="360px">
      <div>确定要删除该帮助文档吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { helpCenterApi } from '@/api/content'
import type { HelpCenter } from '@/types'

const router = useRouter()
const loading = ref(false)
const helpList = ref<HelpCenter[]>([])
const total = ref(0)
const deleteDialogVisible = ref(false)
const deleteId = ref('')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  title: '',
  category: '',
  status: ''
})

// 状态选项
const statusOptions = [
  { value: 'draft', label: '草稿' },
  { value: 'published', label: '已发布' }
]

// 分类选项
const categoryOptions = [
  { value: 'account', label: '账户管理' },
  { value: 'order', label: '订单问题' },
  { value: 'product', label: '商品相关' },
  { value: 'shipping', label: '物流配送' },
  { value: 'payment', label: '支付问题' },
  { value: 'other', label: '其他问题' }
]

// 获取分类名称
const getCategoryName = (category: string) => {
  const found = categoryOptions.find(item => item.value === category)
  return found ? found.label : '未知分类'
}

// 获取分类标签类型
const getCategoryTagType = (category: string) => {
  const map: Record<string, string> = {
    account: 'primary',
    order: 'success',
    product: 'warning',
    shipping: 'danger',
    payment: 'info',
    other: ''
  }
  return map[category] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布'
  }
  return map[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    draft: 'info',
    published: 'success'
  }
  return map[status] || 'info'
}

// 查询帮助文档列表
const getList = async () => {
  loading.value = true
  try {
    const res = await helpCenterApi.getList(queryParams)
    helpList.value = res.list
    total.value = res.total
  } catch (e) {
    ElMessage.error('获取帮助文档失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 添加帮助文档
const handleAdd = () => {
  router.push('/content/help/add')
}

// 编辑帮助文档
const handleUpdate = (row: HelpCenter) => {
  router.push(`/content/help/edit/${row.id}`)
}

// 切换状态
const handleToggleStatus = (row: HelpCenter) => {
  const newStatus = row.status === 'published' ? 'draft' : 'published'
  const statusText = newStatus === 'published' ? '发布' : '下线'
  
  ElMessageBox.confirm(`确定要${statusText}该帮助文档吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 这里可以调用实际的API
      // await helpCenterApi.updateStatus(row.id, newStatus)
      
      // 模拟更新
      const index = helpList.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        helpList.value[index].status = newStatus
      }
      
      ElMessage.success(`${statusText}成功`)
    } catch (error) {
      console.error(`${statusText}帮助文档失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }).catch(() => {})
}

// 删除帮助文档
const handleDelete = async (row: HelpCenter) => {
  try {
    await ElMessageBox.confirm('确定要删除该帮助文档吗？', '提示', { type: 'warning' })
    await helpCenterApi.delete({ id: row.id })
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

// 确认删除
const confirmDelete = async () => {
  try {
    // 这里可以调用实际的API
    // await helpCenterApi.delete(deleteId.value)
    
    // 模拟删除
    helpList.value = helpList.value.filter(item => item.id !== deleteId.value)
    total.value--
    
    ElMessage.success('删除成功')
    deleteDialogVisible.value = false
  } catch (error) {
    console.error('删除帮助文档失败:', error)
    ElMessage.error('删除失败')
  }
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  getList()
}

// 生命周期
onMounted(() => {
  getList()
})

const goTo = (path: string) => router.push(path)
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 